<?php

namespace App\Kuafu\Shop\Service;

use AlibabaCloud\Cloudwf\V20170328\ShopCamera;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Shop\Enum\CameraCacheEnum;
use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\CameraAliWorkLogModel;
use App\Kuafu\Shop\Model\CameraModel;
use App\Kuafu\Shop\Model\Shop;
use App\Library\FeiShu\SendFs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class CameraImportService extends BaseService
{
    public static function dealAliWorkImport(Request $request)
    {
        try {
            // 客流摄像机-设备的DeviceName
            $passIpcDeviceName = $request->get('passIpcDeviceName');
            // 门店编号
            $shopCode = $request->get('shopCode');
            // 普通摄像机-设备的ProductKey
            $normalIpcProductKey = $request->get('normalIpcProductKey');
            // 普通摄像机-设备的DeviceName
            $normalIpcDeviceName = $request->get('normalIpcDeviceName');
            // 客流摄像机-设备的ProductKey
            $passIpcProductKey = $request->get('passIpcProductKey');
            // 客流摄像机-设备SN（客流相机）
            $passlIpcSnList = $request->get('passlIpcSnList');
            // 普通摄像机-通道的ProductKey
            $normalIpcNvrProductKeyList = $request->get('normalIpcNvrProductKeyList');
            // 客流摄像机-通道的ProductKey
            $passIpcNvrProductKeyList = $request->get('passIpcNvrProductKeyList');
            // 普通摄像机-设备SN（摄像机）
            $normalIpcSnList = $request->get('normalIpcSnList');
            // 普通摄像机-摄像机所在位置
            $normalIpcPositionList = $request->get('normalIpcPositionList');
            // 客流摄像机-摄像机所在位置
            $passIpcPositionList = $request->get('passIpcPositionList');
            // 客流摄像机-通道的DeviceName
            $passIpcNvrDeviceNameList = $request->get('passIpcNvrDeviceNameList');
            // 普通摄像机-通道的DeviceName
            $normalIpcNvrDeviceNameList = $request->get('normalIpcNvrDeviceNameList');
            // WIFI摄像机-摄像机所在位置
            $wifiIpcPositionList = $request->get('wifiIpcPositionList');
            // WIFI摄像机 - PK 列表
            $wifiIpcProductKey = $request->get('wifiIpcProductKey');
            // WIFI摄像机 - SN 列表
            $wifiIpcSnList = $request->get('wifiIpcSnList');
            // WIFI摄像机 - DN 列表
            $wifiIpcDeviceName = $request->get('wifiIpcDeviceName');

            // nvrDeviceName -- DeviceName
            // nvrProductKey -- ProductKey
            // nvrSerialNumber -- SN（NVR）
            // nvrScreenShort -- 录像策略截图
            // passIpcScreenShortList -- 客流摄像机-编码格式及码率截图
            // normalIpcChannelNumList -- 普通摄像机-通道序号（NVR中）
            // nvrChannelPicture -- NVR通道截图
            // passIpcPictureList -- 客流摄像机-设备放置图片
            // passIpcChannelNumList -- 客流摄像机-通道序号（NVR中）
            // normalIpcScreenShortList -- 普通摄像机-编码格式及码率截图
            // acceptancePicture -- 客户签字验收单
            // nvrPicture -- nvr 设备放置图片
            // normalIpcPictureList -- 普通摄像机-设备放置图片
            // passIpcVideoList -- 客流摄像机-设备视频画面
            // normalIpcVideoList -- 普通摄像机-设备视频画面
            // wifiIpcPictureList --WIFI 摄像头放置图片

            $result = [
                'allParams' => $request->all()
            ];
            \Illuminate\Support\Facades\Log::info('aliwork', $result);

            if (empty($shopCode)) {
                return;
            }

            // 请求日志
            CameraAliWorkLogModel::query()->create([
                'shopCode'   => $shopCode,
                'requestLog' => json_encode($request->all())
            ]);


            // 处理关键数据
            // 普通摄像机
            $normalIpcNvrDeviceNameList = array_filter(json_decode($normalIpcNvrDeviceNameList, 1));
            $normalIpcNvrProductKeyList = array_filter(json_decode($normalIpcNvrProductKeyList, 1));
            $normalIpcProductKey        = array_filter(json_decode($normalIpcProductKey, 1));
            $normalIpcDeviceName        = array_filter(json_decode($normalIpcDeviceName, 1));
            $normalIpcSnList            = array_filter(json_decode($normalIpcSnList, 1));
            $normalIpcPositionList      = array_filter(json_decode($normalIpcPositionList, 1));

            // 客流像机
            $passlIpcSnList           = array_filter(json_decode($passlIpcSnList, 1));
            $passIpcPositionList      = array_filter(json_decode($passIpcPositionList, 1));
            $passIpcNvrDeviceNameList = array_filter(json_decode($passIpcNvrDeviceNameList, 1));
            $passIpcNvrProductKeyList = array_filter(json_decode($passIpcNvrProductKeyList, 1));
            $passIpcDeviceName        = array_filter(json_decode($passIpcDeviceName, 1));
            $passIpcProductKey        = array_filter(json_decode($passIpcProductKey, 1));

            // WIFI 摄像机
            $wifiIpcPositionList = array_filter(json_decode($wifiIpcPositionList, 1));
            $wifiIpcProductKey   = array_filter(json_decode($wifiIpcProductKey, 1));
            $wifiIpcSnList       = array_filter(json_decode($wifiIpcSnList, 1));
            $wifiIpcDeviceName   = array_filter(json_decode($wifiIpcDeviceName, 1));

            $shopInfo = Shop::query()->where('shopCode', $shopCode)->first();

            // 设备名称
            $insertData = [

            ];

            if (!empty($normalIpcDeviceName)) {
                // 普通摄像机数据
                foreach ($normalIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_2,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_1,
                        'name'         => vsprintf("普通-TC-112FN(%s)", [$normalIpcPositionList[$key] ?? '']),
                        // 普通摄像机名字写死
                        'serialNo'     => $normalIpcSnList[$key] ?? '',
                        // SN,
                        'deviceName'   => $normalDn,
                        //DN,
                        'productKey'   => $normalIpcProductKey[$key],
                        // PK,
                        'deviceSecret' => '',
                        // DS,
                        'mac'          => $normalIpcSnList[$key] ?? '',
                        // MAC,
                        'createdAt'    => time(),
                    ];
                }
                // 通道三元组
                foreach ($normalIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_2,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_2,
                        'name'         => vsprintf("普通-TC-112FN(%s)", [$normalIpcPositionList[$key] ?? '']),
                        // 普通摄像机名字写死
                        'serialNo'     => $normalIpcSnList[$key] ?? '',
                        // SN,
                        'deviceName'   => $normalIpcNvrDeviceNameList[$key] ?? '',
                        //DN,
                        'productKey'   => $normalIpcNvrProductKeyList[$key] ?? '',
                        // PK,
                        'deviceSecret' => '',
                        // DS,
                        'mac'          => $normalIpcSnList[$key] ?? '',
                        // MAC
                        'createdAt'    => time(),
                    ];
                }
            }

            if (!empty($passIpcDeviceName)) {
                // 客流摄像机数据
                foreach ($passIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_1,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_1,
                        'name'         => vsprintf("客流-TC-C52SW(%s)", [$passIpcPositionList[$key]]),   // 普通摄像机名字写死
                        'serialNo'     => $passlIpcSnList[$key] ?? '', // SN,
                        'deviceName'   => $normalDn, //DN,
                        'productKey'   => $passIpcProductKey[$key], // PK,
                        'deviceSecret' => '', // DS,
                        'mac'          => $passlIpcSnList[$key] ?? '', // MAC
                        'createdAt'    => time(),
                    ];
                }
                // 客流三元组数据
                foreach ($passIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_1,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_2,
                        'name'         => vsprintf("客流-TC-C52SW(%s)", [$passIpcPositionList[$key]]),   // 普通摄像机名字写死
                        'serialNo'     => $passlIpcSnList[$key] ?? '', // SN,
                        'deviceName'   => $passIpcNvrDeviceNameList[$key], //DN,
                        'productKey'   => $passIpcNvrProductKeyList[$key], // PK,
                        'deviceSecret' => '', // DS,
                        'mac'          => $passlIpcSnList[$key] ?? '', // MAC
                        'createdAt'    => time(),
                    ];
                }
            }

            if (!empty($wifiIpcDeviceName)) {
                // 客流摄像机数据
                foreach ($wifiIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_1,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_1,
                        'name'         => vsprintf("WIFI-C2HK(%s)", [$wifiIpcPositionList[$key]]),   // 普通摄像机名字写死
                        'serialNo'     => $wifiIpcSnList[$key] ?? '', // SN,
                        'deviceName'   => $normalDn, //DN,
                        'productKey'   => $wifiIpcProductKey[$key], // PK,
                        'deviceSecret' => '', // DS,
                        'mac'          => $wifiIpcSnList[$key] ?? '', // MAC
                        'createdAt'    => time(),
                    ];
                }
                // 客流三元组数据
                foreach ($wifiIpcDeviceName as $key => $normalDn) {
                    $insertData[] = [
                        'shopId'       => $shopInfo->id,
                        'supplier'     => CameraModel::SUPPLIER_ALIYUN,
                        'type'         => CodeEnum::SHOP_CAMERA_TYPE_1,
                        'tripleType'   => CodeEnum::SHOP_CAMERA_TRIPLE_TYPE_2,
                        'name'         => vsprintf("WIFI-C2HK(%s)", [$wifiIpcPositionList[$key]]),   // 普通摄像机名字写死
                        'serialNo'     => $wifiIpcSnList[$key] ?? '', // SN,
                        'deviceName'   => $normalDn, //DN,
                        'productKey'   => $wifiIpcProductKey[$key], // PK,
                        'deviceSecret' => '', // DS,
                        'mac'          => $wifiIpcSnList[$key] ?? '', // MAC
                        'createdAt'    => time(),
                    ];
                }
            }
            // 去除无效数据
            $uniqueInsertData = [];
            foreach ($insertData as $datum) {
                if (empty($datum['deviceName'])) {
                    continue;
                }
                $uniqueInsertData[$datum['deviceName'] . '_' . $datum['tripleType']] = $datum;
            }
            $insertData = array_values($uniqueInsertData);

            // 判断长度
            if (count($insertData) > 0) {
                CameraModel::query()->where('shopId', $shopInfo->id)
                           ->where('supplier', CameraModel::SUPPLIER_ALIYUN)
                           ->update([
                               'isDeleted' => 1
                           ]);
                CameraModel::query()->insert($insertData);
                \Illuminate\Support\Facades\Cache::forget(CameraCacheEnum::getCameraListCacheKey($shopInfo->id));

            }

            if (isTest()) {
                SendFs::newRobot()
                      ->setTitleContent('阿里云宜搭设备更新',
                          "{$shopInfo->name}({$shopInfo->shopCode}) 推送" . count($insertData) / 2 . '台设备')
//                      ->setAtUid('3fgc8798')
                      ->setAtUid('2c54915f')
                      ->send();
            } else {
                SendFs::newRobot(SendFs::ROBOT_ALI_WORK_SYNC)
                      ->setTitleContent('阿里云宜搭设备更新',
                          "{$shopInfo->name}({$shopInfo->shopCode}) 推送" . count($insertData) / 2 . '台设备')
//                      ->setAtUid('3fgc8798')
                      ->setAtUid('2c54915f')
                      ->send();
            }

        } catch (\Exception $exception) {
            Log::error('宜搭推送数据异常', [
                'msg' => $exception->getMessage()
            ]);

            if (isTest()) {
                SendFs::newRobot()
                      ->setTitleContent('阿里云宜搭设备更新失败',
                          json_encode([
                              'file' => $exception->getFile(),
                              'msg'  => $exception->getMessage(),
                              'line' => $exception->getLine()
                          ]))
//                      ->setAtUid('3fgc8798')
                      ->setAtUid('2c54915f')
                      ->send();
            } else {
                SendFs::newRobot(SendFs::ROBOT_ALI_WORK_SYNC)
                      ->setTitleContent('阿里云宜搭设备更新失败',
                          json_encode([
                              'file' => $exception->getFile(),
                              'msg'  => $exception->getMessage(),
                              'line' => $exception->getLine()
                          ]))
//                      ->setAtUid('3fgc8798')
                      ->setAtUid('2c54915f')
                      ->send();
            }


        }
    }

}
